﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Lavka.Models;

namespace Lavka.Controllers
{ 
    public class PagesController : Controller
    {
        private LavkaDbEntities db = new LavkaDbEntities();

        //
        // GET: /Pages/

        public ViewResult Index()
        {
            return View(db.Pages.ToList());
        }

        //
        // GET: /Pages/Details/5

        public ViewResult Details(int id)
        {
            Pages pages = db.Pages.Single(p => p.PageId == id);
            return View(pages);
        }

        //
        // GET: /Pages/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Pages/Create

        [HttpPost]
        public ActionResult Create(Pages pages)
        {
            if (ModelState.IsValid)
            {
                db.Pages.AddObject(pages);
                db.SaveChanges();
                return RedirectToAction("Index");  
            }

            return View(pages);
        }
        

        public ActionResult Edit(string path)
        {
            Pages pages = null;
            try
            {
                pages = db.Pages.Single(p => p.Path == path);
            }
            catch (InvalidOperationException ex)
            {
                pages = new Pages()
                            {
                                Path = path
                            };
                db.Pages.AddObject(pages);
                db.SaveChanges();
            }
            return View(pages);
        }

        //
        // POST: /Pages/Edit/5

        [HttpPost]
        public ActionResult Edit(Pages pages)
        {
            if (ModelState.IsValid)
            {
                db.Pages.Attach(pages);
                db.ObjectStateManager.ChangeObjectState(pages, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(pages);
        }

        //
        // GET: /Pages/Delete/5
 
        public ActionResult Delete(int id)
        {
            Pages pages = db.Pages.Single(p => p.PageId == id);
            return View(pages);
        }

        //
        // POST: /Pages/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {            
            Pages pages = db.Pages.Single(p => p.PageId == id);
            db.Pages.DeleteObject(pages);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}